package com.unohacha.qqj.fzdr.main;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppFzSchoolBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeBannerBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeLatestBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeLocationYPageBean;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.util.GlideImageLoader;
import com.unohacha.qqj.fzdr.util.MyUtils;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;
import com.unohacha.qqj.mylibrary.listener.PoponDismissListener;
import com.unohacha.qqj.mylibrary.view.ConfirmPopWindow;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 本地黄页 item_location_page
 */
public class LocationYPageActivity extends BaseActivity implements OnRefreshLoadmoreListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.pt_tabs)
    TabLayout mTabLayout;
    @BindView(R.id.car_list_recycler)
    RecyclerView carListRecycler;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.title_ll)
    LinearLayout titleLl;
    @BindView(R.id.common_cancle)
    ImageView commonCancle;
    @BindView(R.id.edt_seach)
    EditText edtSeach;
    @BindView(R.id.common_right_search)
    TextView commonRightSearch;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.pt_line)
    ImageView ptLine;
    @BindView(R.id.send_iv)
    ImageView sendIv;
    @BindView(R.id.banner)
    Banner banner;

    private List<String> mFragmentsTitle = new ArrayList<String>();//碎片的标题
    private List<HomeAppFzSchoolBean.DataBean> mCateList = new ArrayList<>();
    private List<HomeBannerBean.DataBean> mBannerAllList = new ArrayList<>();//banner的集合
    private List<String> mBannerList = new ArrayList<>();
    private int page = 1;
    private int id = 54;// 54 是本地黄页的id
    private int app_cate_id;//分类ID
    private List<HomeLocationYPageBean.DataBeanX.DataBean> mYPageList = new ArrayList<>();
    private BaseRVAdapter mBaseAdapter;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 10086;
    private static final int MY_SEND_PAGE = 10007;//发布本地黄页的

    @Override
    protected int getLayoutId() {
        return R.layout.activity_location_ypage;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setText(getResources().getString(R.string.locate_yellow_page));
        commonRightText.setVisibility(View.GONE);
        commonRightImage.setVisibility(View.VISIBLE);
        commonRightImage.setImageResource(R.drawable.ic_search_black);

        initRefreshLayout();
        getAppCateList();
        getBannerData(37);//本地黄页id 37
    }

    private void initRefreshLayout() {
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        carListRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    //获取banner 集合数据
    private void getBannerData(int typeid) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("typeid", typeid);//4-面料供求 5-制造供求 6-原料供求 7-辅料供应 8-人才招聘 29-求职发布
        XUtil.Post(UrlConfig.AD_LIST, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.resetNoMoreData();
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))) {
                        Gson gson = new Gson();
                        HomeBannerBean bannerBean = gson.fromJson(result, HomeBannerBean.class);
                        if (null != bannerBean) {
                            if (null != mBannerAllList) {
                                mBannerAllList.clear();
                            }
                            mBannerAllList.addAll(bannerBean.getData());
                            setBannerData();
                        }
                        mRefreshLayout.finishLoadmore();
                        mRefreshLayout.finishLoadmoreWithNoMoreData();
                    } else if ("100".equals(jsonObject.optString("code"))) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //设置banner 数据
    private void setBannerData() {
        if (null != mBannerAllList) {
            for (int i = 0; i < mBannerAllList.size(); i++) {
                mBannerList.add(i, mBannerAllList.get(i).getImg_face());
            }
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);//设置圆形指示器与标题
            banner.setIndicatorGravity(BannerConfig.CENTER);//设置指示器位置
            banner.setImages(mBannerList);
            banner.setImageLoader(new GlideImageLoader());
            banner.start();

            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    //用mBannerAllList集合
                }
            });
        }
    }


    //初始化tab
    private void initTabLayout(List<String> mFragmentsTitle0) {

        for (int i = 0; i < mFragmentsTitle0.size(); i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(mFragmentsTitle.get(i)), i);
        }

        if (null != mCateList) {
            app_cate_id = mCateList.get(0).getId();
        }
        getCateDataList("");
        
        mTabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.black));
        mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                app_cate_id = mCateList.get(tab.getPosition()).getId();
                page = 1;
                getCateDataList("");
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    //获取本地黄页的分类标题
    private void getAppCateList(){
        Map<String,Object> params = new HashMap<>();
        params.put("id",54);
        XUtil.Post(UrlConfig.APP_CATE_LIST,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")){
                        Gson gson = new Gson();
                        HomeAppFzSchoolBean schoolBean = gson.fromJson(result,HomeAppFzSchoolBean.class);
                        if (null != schoolBean){
                            if (null != mCateList){
                                mCateList.clear();
                            }
                            mCateList.addAll(schoolBean.getData());
                            for (int i = 0; i < mCateList.size(); i++) {
                                mFragmentsTitle.add(i,mCateList.get(i).getName());
                            }
                            initTabLayout(mFragmentsTitle);
                        }
                    }else if (100 == jsonObject.optInt("code")){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }
    
    //获取本地黄页的列表数据
    private void getCateDataList(String keyword){
        Map<String,Object> params = new HashMap<>();
        params.put("app_cate_id",app_cate_id);
        params.put("keyword",keyword);
        params.put("address_id",Prefer.obtainReLocation(this));
        params.put("page",page);
        XUtil.Post(UrlConfig.APP_LOCATION_YELLOW_LIST,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("TAG: getCateDataList:",result.toString());
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")){
                        Gson gson = new Gson();
                        HomeLocationYPageBean yPageBean = gson.fromJson(result,HomeLocationYPageBean.class);
                        if (null != yPageBean){
                            if (page == 1){
                                if (null != mYPageList){
                                    mYPageList.clear();
                                }
                                
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.resetNoMoreData();
                                
                                mYPageList.addAll(yPageBean.getData().getData());
                                
                            }else {
                                mRefreshLayout.finishLoadmore();
                                mBaseAdapter.notifyDataSetChanged();
                            }

                            setLocationYPageAdapter();
                        }
                    }else if (100 == jsonObject.optInt("code")){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        if (page == 1){
                            MyToast(jsonObject.optString("message"));
                            if (null != mYPageList){
                                mYPageList.clear();
                            }
                            mBaseAdapter.notifyDataSetChanged();
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                        }else {
                            MyToast(getResources().getString(R.string.no_more_data));
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }
    
    private void setLocationYPageAdapter(){
        mBaseAdapter = new BaseRVAdapter(this,mYPageList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_location_page;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                TextView tv_name = holder.getTextView(R.id.tv_name);
                TextView tv_phone = holder.getTextView(R.id.tv_phone);
                TextView tv_address = holder.getTextView(R.id.tv_address);
                if (null != mYPageList){
                    tv_name.setText(mYPageList.get(position).getCompany_name());
                    tv_address.setText("地址：" + mYPageList.get(position).getProvince() + mYPageList.get(position).getCity() 
                            + mYPageList.get(position).getArea() + mYPageList.get(position).getDetailed_address());
                    tv_phone.setText(mYPageList.get(position).getTelephone());
                }
                
            }
        };
        mBaseAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                //打电话
               final String phoneNum = mYPageList.get(position).getTelephone();
               Log.e("TAG: 手机号 " ,phoneNum);
                if (!TextUtils.isEmpty(phoneNum)){
                    
                    if (null == confirmPop){
                        confirmPop =  new ConfirmPopWindow(LocationYPageActivity.this,LocationYPageActivity.this);
                    }
                    confirmPop.showUi("是否拨打" + phoneNum,"取消","确定");
                    confirmPop.showAtLocation(carListRecycler, Gravity.CENTER,0,0);
                    confirmPop.setConfirmListener(new ConfirmPopWindow.OnConfirmListener() {
                        @Override
                        public void onSure() {

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                                    && ContextCompat.checkSelfPermission(LocationYPageActivity.this,
                                    Manifest.permission.CALL_PHONE)
                                    != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(LocationYPageActivity.this,
                                        new String[]{Manifest.permission.CALL_PHONE},
                                        MY_PERMISSIONS_REQUEST_CALL_PHONE);
                            } else {
                                Intent intent2 = new Intent(Intent.ACTION_DIAL);
                                Uri data = Uri.parse("tel:" + phoneNum);
                                intent2.setData(data);
                                startActivity(intent2);
                            }
                        }

                        @Override
                        public void onCancel() {
                            MyToast("取消");
                            confirmPop.dismissView();
                        }
                    });
                    confirmPop.setOnDismissListener(new PoponDismissListener(LocationYPageActivity.this));
                }
            }
        });
        carListRecycler.setAdapter(mBaseAdapter);
    }
    
    @OnClick({R.id.common_back,R.id.common_right_image,
            R.id.common_cancle,R.id.common_right_search,
            R.id.send_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;

            case R.id.common_right_image://搜索
                searchLl.setVisibility(View.VISIBLE);
                edtSeach.setText("");
                titleLl.setVisibility(View.GONE);
                break;
            case R.id.common_cancle://取消
                searchLl.setVisibility(View.GONE);
                titleLl.setVisibility(View.VISIBLE);
                edtSeach.setText("");
                break;
            case R.id.common_right_search://搜索按钮
                if (!TextUtils.isEmpty(edtSeach.getText().toString().trim())) {
                    getCateDataList(edtSeach.getText().toString().trim());
                }else {
                   MyToast("请输入搜索内容!");
                   return;
                }
                break;
            case R.id.send_iv://发布
                Intent intent = new Intent(this,LocationYellowSendActivity.class);
                intent.putExtra("app_cate_id",app_cate_id);
                startActivityForResult(intent,MY_SEND_PAGE);
                break;
        }
    }

    
    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                getCateDataList("");
            }
        }, 2000);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                getCateDataList("");
            }
        }, 2000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MY_SEND_PAGE){
            page = 1;
            getCateDataList("");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    
}
